package com.dzwww.recommend.rule.common.api;

import com.dzwww.recommend.rule.util.StringPlaceholderFormatter;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;

/**
 * 断言工具类，配合 {@link ApiException} 使用
 * @author winner
 */
public class ApiAsserts {

	public static void isTrue(boolean expression, String code, String message, Object... args) {
		if(!expression) {
			throw new ApiException(code, StringPlaceholderFormatter.format(message, args));
		}
	}
	
	public static void isTrue(boolean expression, ApiMessage errorMessage, Object... args) {
		if(!expression) {
			throw new ApiException(errorMessage, args);
		}
	}

	public static void notBlank(String text, String code, String message, Object... args) {
		isTrue(StringUtils.isNotBlank(text), code, message, args);
	}

	public static void notBlank(String text, ApiMessage errorMessage, Object... args) {
		isTrue(StringUtils.isNotBlank(text), errorMessage, args);
	}

	public static void notNull(Object object, String code, String message, Object... args) {
		isTrue(object != null, code, message, args);
	}

	public static void notNull(Object object, ApiMessage errorMessage, Object... args) {
		isTrue(object != null, errorMessage, args);
	}

	public static void notEmpty(Collection<?> collection, String code, String message, Object... args) {
		isTrue(collection != null && !collection.isEmpty(), code, message, args);
	}

	public static void notEmpty(Collection<?> collection, ApiMessage errorMessage, Object... args) {
		isTrue(collection != null && !collection.isEmpty(), errorMessage, args);
	}

	public static void notEmpty(Object[] array, String code, String message, Object... args) {
		isTrue(array != null && array.length > 0, code, message, args);
	}

	public static void notEmpty(Object[] array, ApiMessage errorMessage, Object... args) {
		isTrue(array != null && array.length > 0, errorMessage, args);
	}
	
	public static void noNullElements(Object[] array, String code, String message, Object... args) {
		isTrue(hasNullElement(array), code, message, args);
	}

	public static void noNullElements(Object[] array, ApiMessage errorMessage, Object... args) {
		isTrue(hasNullElement(array), errorMessage, args);
	}
	
	private static boolean hasNullElement(Object[] array) {
		if (array != null) {
			for (Object element : array) {
				if (element == null) {
					return true;
				}
			}
		}
		return false;
	}

	public static void noNullElements(Collection<?> collection, String code, String message, Object... args) {
		isTrue(hasNullElement(collection), code, message, args);
	}

	public static void noNullElements(Collection<?> collection, ApiMessage errorMessage, Object... args) {
		isTrue(hasNullElement(collection), errorMessage, args);
	}
	
	private static boolean hasNullElement(Collection<?> collection) {
		if (collection != null) {
			for (Object element : collection) {
				if (element == null) {
					return true;
				}
			}
		}
		return false;
	}
}
